import { put, call } from 'redux-saga/effects';
import { startLoading, stopLoading } from '../saga-loading';
import { errorAction } from '../actions';

function* defaultErrorHandler(error, action) {
  yield put(errorAction.error(error, action));
}

export function safe(saga, namespace, errorHandler = defaultErrorHandler) {
  return function*(action) {
    const modelNames = [];
    if (namespace) {
      modelNames.push(namespace);
    }
    if (action) {
      modelNames.push(action.type);
    }
    try {
      yield startLoading(...modelNames);
      yield call(saga, action);
    } catch (error) {
      yield errorHandler(error, action);
    } finally {
      yield stopLoading(...modelNames);
    }
  };
}
